<span th:replace="layout/header::common_header" xmlns:th="http://www.w3.org/1999/xhtml"
      xmlns:shiro="http://www.w3.org/1999/xhtml"></span>
<style>
    .bootstrap-table .fixed-table-container .fixed-table-body {
        height: auto !important;
    }
</style>
<!--页面主要内容-->
<main class="lyear-layout-content" xmlns:th="http://www.w3.org/1999/xhtml">

    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="panel panel-default">
                        <div class="panel-body">
                            <form id="formSearch" class="form-horizontal">
                                <div class="form-group" style="margin-top:15px">
                                    <div class="row col-sm-12">
                                        <label class="control-label col-sm-1" for="txt_search_name">角色名称</label>
                                        <div class="col-sm-2">
                                            <input type="text" class="form-control" id="txt_search_name" value="">
                                        </div>
                                        <div class="col-sm-2" style="text-align:left;">
                                            <button type="button" style="margin-left:50px" class="btn btn-primary"
                                                    onclick="refreshData(this)">查询
                                            </button>
                                        </div>
                                    </div>
                            </form>
                        </div>
                    </div>
                    <div id="toolbar" class=" toolbar-btn-action">
                        <div style="display: contents" shiro:hasPermission="role:add">
                            <a class="btn btn-primary m-r-5" href="#" id="shiro-add" data-toggle="modal"
                               data-target="#addModal"><i class="mdi mdi-plus"></i> 新增</a>
                        </div>
                        <div style="display: contents" shiro:hasPermission="role:edit">
                            <a class="btn btn-warning m-r-5" href="#!" id="shiro-edit" onclick="ShowDiv('EditDiv')"><i
                                    class="mdi mdi-block-helper"></i>编辑</a>
                        </div>
                        <div style="display: contents" shiro:hasPermission="role:delete">
                            <a class="btn btn-danger" href="#!" id="shiro-delete" onclick="ShowDiv('DelDiv')"><i
                                    class="mdi mdi-window-close"></i> 删除</a>
                        </div>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-bordered" id="tb_departments"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- add模态框（Modal） -->
    <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title" id="myModalLabel">添加</h4>
                </div>
                <div class="modal-body ">
                    <form class="form-horizontal" id="addformData" role="form">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">角色名称</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" name="name" value=""
                                       placeholder="角色名称">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">描述</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" name="description" value=""
                                       placeholder="请输入描述">
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary " onclick="addData()">提交</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div>
    <!-- edit模态框（Modal） -->
    <div class="modal fade" id="editModel" tabindex="-1" role="dialog" aria-labelledby="myModalEeditLabel"
         aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title" id="myModalEeditLabel">编辑</h4>
                </div>
                <div class="modal-body ">
                    <form class="form-horizontal" id="editformData" role="form">
                        <input type="hidden" name="id" value=""/>
                        <div class="form-group">
                        <label class="col-sm-2 control-label">角色名称</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="name" value=""
                                   placeholder="角色名称">
                        </div>
                    </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">描述</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" name="description" value=""
                                       placeholder="请输入描述">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">是否可用</label>
                            <div class="col-sm-10 example-box">
                                <label class="lyear-radio radio-inline radio-primary">
                                    <input type="radio" class="yes-available" name="available" value="1"
                                           checked="true"><span>是</span>
                                </label>
                                <label class="lyear-radio radio-inline radio-primary">
                                    <input type="radio" class="false-available" name="available" value="0"><span>否</span>
                                </label>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary " onclick="editData()">提交</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div>
    <!-- role模态框（Modal） -->
    <div class="modal fade" id="roleModel" tabindex="-1" role="dialog" aria-labelledby="myModalroleLabel"
         aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title" id="myModalroleLabel">分配权限管理</h4>
                </div>
                <div class="modal-body ">
                    <form id="boxRoleForm">
                        <input type="hidden" name="roleId" value=""/>
                        <div class="zTreeDemoBackground left">
                            <ul id="treeDemo" class="ztree"></ul>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary " onclick="roleData()">提交</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div>
    </div>
    <div id="operateDiv" style="display: none;">
        <div style="display: contents" shiro:hasPermission="role:edit">
            <a href="javascript:void(0);" id="edit_" uniqueId=""><span class="glyphicon glyphicon-pencil" title="修改"></span></a>

        </div>
        <div style="display: contents" shiro:hasPermission="role:delete">
            <a href="javascript:void(0);" id="del_" uniqueId=""><span class="glyphicon glyphicon-trash" title="删除"></span></a>
        </div>
        <div style="display: contents" shiro:hasPermission="role:allotResource">
            <a href="javascript:void(0);" id="allot_" uniqueId=""><span class="glyphicon  glyphicon-th-list" title="分配权限管理"></span></a>
        </div>

    </div>
</main>
<!--End 页面主要内容-->
<span th:replace="layout/footer::common_footer" xmlns:th="http://www.w3.org/1999/xhtml"></span>
<script type="text/javascript">
    //关闭add模态框，清空表单
    $('body').on('hidden.bs.modal', '#addModal', function () {
        document.getElementById("addformData").reset();
        // $(this).removeData('bs.modal');

    });

    //添加数据
    function addData() {
        //提交数据
        var data = $('#addformData').serializeArray();
        $.ajax({
            url: "/roles/addPost",
            async: false,
            type: 'post',
            data: data,
            success: function (e) {
                //200成功， 500错误
                if (e.status == 200) {
                    layer.msg(e.message, {icon: 1, time: 2000}, function (index) {
                        if (e.status == 200) {
                            //关闭对话框
                            $("#addModal").modal("hide");
                            //清空模态框（Modal）表单
                            document.getElementById("addformData").reset();
                            //刷新表格
                            $("#tb_departments").bootstrapTable('refresh');
                        }
                    });
                } else {
                    layer.msg(e.message, {icon: 2, time: 2000});
                }

            }
        });
    }
</script>
<!--编辑删除-->
<script type="text/javascript">
    //关闭edit模态框，清空表单
    $('body').on('hidden.bs.modal', '#editModal', function () {
        document.getElementById("editformData").reset();
    });

    //保存修改
    function editData() {
        //提交数据
        var data = $('#editformData').serializeArray();
        $.ajax({
            url: "/roles/editPost",
            async: false,
            type: 'post',
            data: data,
            success: function (e) {
                //200成功， 500错误
                if (e.status == 200) {
                    layer.msg(e.message, {icon: 1, time: 2000}, function (index) {
                        if (e.status == 200) {
                            //关闭对话框
                            $("#editModel").modal("hide");
                            //清空模态框（Modal）表单
                            document.getElementById("editformData").reset();
                            //刷新表格
                            $("#tb_departments").bootstrapTable('refresh');
                        }
                    });
                } else {
                    layer.msg(e.message, {icon: 2, time: 2000});
                }

            }
        });
    }

    //弹出隐藏层：修改， 删除
    function ShowDiv(show_div) {
        var selectedRow = $('#tb_departments').bootstrapTable('getSelections');
        selectedRow = selectedRow[0];
        if (selectedRow == null || selectedRow.length == 0) {
            layer.msg("请选择要修改的记录");
            return false;
        }
        if (show_div == "EditDiv") {
            //模态框赋值
            $("#editformData input[name='id']").val(selectedRow.id);
            $("#editformData input[name='name']").val(selectedRow.name);
            $("#editformData input[name='description']").val(selectedRow.description);
            //可用状态
            var available = selectedRow.available;
            if (available == 1) {
                $(".yes-available").trigger("click");
            }
            if (available == 0) {
                $(".false-available").trigger("click");
            }

            //显示编辑模态框
            $("#editModel").modal("show");
        }

        //删除
        if (show_div == 'DelDiv') {
            //询问框
            layer.confirm('确定要删除吗？', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                $.ajax({
                    url: "/roles/delPost",
                    async: false,
                    type: 'post',
                    data: {id: selectedRow.id},
                    success: function (e) {
                        if (e.status == 200) {
                            layer.msg(e.message, {icon: 1, time: 2000}, function (index) {
                                //刷新表格
                                $("#tb_departments").bootstrapTable('refresh');
                            });
                        } else {
                            layer.msg(e.message, {icon: 2, time: 2000});
                        }
                    }
                });
            }, function () {
                layer.closeAll('dialog');
            });
        }
    };

    //编辑行:对修改按钮绑定事件
    $("#tb_departments").on("click", "[id^='edit_']", function () {
        //点击获取行信息
        var uniqueId = $(this).attr("uniqueId");
        var aa = $("#tb_departments").bootstrapTable('getRowByUniqueId', uniqueId);

        ShowDiv("EditDiv");
    });

    //删除行
    $("#tb_departments").on("click", "[id^='del_']", function () {
        //主键id
        var uniqueId = $(this).attr("uniqueId");
        //获取单行信息
        var aa = $("#tb_departments").bootstrapTable('getRowByUniqueId', uniqueId);

        ShowDiv("DelDiv");
    });



</script>

<script type="text/javascript">

    //操作按钮权限控制
    function getPermission(value, row, index) {
        var html = "";
        $("#operateDiv").find("a").each(function () {
            var _srcid = $(this).attr("id");
            var _id = _srcid + index;
            var _uniqueId = row.id;
            $(this).attr("id", _id);//笔者对按钮的id属性进行赋值
            $(this).attr("uniqueId", _uniqueId);//笔者对按钮的uniqueId属性进行赋值
            html += this.outerHTML + "&nbsp;&nbsp;&nbsp;&nbsp;";
            $(this).attr("id", _srcid);
        });
        return html;
    }

    $(function () {
        //1.初始化Table
        var oTable = new TableInit();
        oTable.Init();

        //2.初始化Button的点击事件
        var oButtonInit = new ButtonInit();
        oButtonInit.Init();
    });

    var ButtonInit = function () {
        var oInit = new Object();
        var postdata = {};

        oInit.Init = function () {
            //初始化页面上面的按钮事件
        };
        return oInit;
    };
    var TableInit = function () {
        var oTableInit = new Object();
        //初始化Table
        oTableInit.Init = function () {
            $('#tb_departments').bootstrapTable({
                url: "/roles/list",         //请求后台的URL（*）
                method: 'get',                      //请求方式（*）
                toolbar: '#toolbar',                //工具按钮用哪个容器
                striped: true,                      //是否显示行间隔色
                cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,                   //是否显示分页（*）
                sortable: true,                     //是否启用排序
                sortOrder: "desc",                   //排序方式
                queryParams: oTableInit.queryParams,//传递参数（*）
                sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1,                       //初始化加载第一页，默认第一页
                pageSize: 10,                       //每页的记录行数（*）
                pageList: [5, 10, 25, 50, 100],        //可供选择的每页的行数（*）
                search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
                strictSearch: false,
                showColumns: false,                  //是否显示所有的列
                showRefresh: false,                  //是否显示刷新按钮
                minimumCountColumns: 2,             //最少允许的列数
                clickToSelect: true,                //是否启用点击选中行
                singleSelect: true,                  //开启单选按钮
                // height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
                uniqueId: "id",                     //每一行的唯一标识，一般为主键列
                showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
                cardView: false,                    //是否显示详细视图
                detailView: false,                   //是否显示父子表
                columns: [{
                    checkbox: true
                }, {
                    field: 'id',
                    title: 'id'
                }, {
                    field: 'name',
                    title: '角色名称'
                }, {
                    field: 'description',
                    title: '描述'
                }, {
                    field: 'available',
                    title: '可用'
                }, {
                    field: 'operate',
                    title: '操作',
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value, row, index) {
                        return getPermission(value, row, index);
                    }
                }]
            });
        };

        //表格搜索：查询的参数
        oTableInit.queryParams = function (params) {
            var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                limit: params.limit,   //页面大小
                offset: params.offset,  //页码
                page: params.offset / params.limit + 1,
                // search: params.search, //表格搜索
                sort: params.order, //排序
                username: $("#txt_search_departmentname").val(), //查询的参数
                status: $("#txt_search_status").val(),
            };
            return temp;
        };

        oTableInit.refresh = function () {
            $("#tb_departments").bootstrapTable('refresh', {
                url: "/roles/list",
            })
        }
        return oTableInit;
    };



    //搜索查询
    function refreshData() {
        //获取表格的参数
        var ta = $("#tb_departments").bootstrapTable('getOptions');
        // console.log(ta); //获取bootstrap columns属性
        $("#tb_departments").bootstrapTable('refreshOptions', {
            columns: ta.columns,
            url: "/roles/list",
            pageNumber: 1, //再次查询的起始页从第1页开始显示
            queryParams: function (params) {
                return {
                    limit: params.limit,   //页面大小
                    offset: params.offset,  //页码
                    rows: params.limit, //页面大小
                    page: params.offset / params.limit + 1,
                    name: $("#txt_search_name").val(),  //资源名称
                    url: $("#txt_search_url").val(),  //资源url
                    permission: $("#txt_search_permission").val(),    //资源权限
                }
            },
        });
    };

</script>
<!-- 分配权限 -->
<script type="text/javascript">
    //关闭role模态框，清空表单
    $('body').on('hidden.bs.modal', '#roleModel', function () {
        document.getElementById("boxRoleForm").reset();
    });

    //提交修改权限
    function roleData() {
        //获取选中的复选框
        var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
            checkCount = zTree.getCheckedNodes(true);
        var resourcesIds = new Array();
        for(var i=0;i<checkCount.length; i++){
            resourcesIds.push(checkCount[i].id);
        }
        var roleId = $("#roleModel input[name='roleId']").val();
        // console.log(resourcesIds);
        $.ajax({
            url:"/roles/saveRoleResources",
            async:false,
            type:"post",
            data:{roleId:roleId, resourcesIds:resourcesIds.join(',')},
            success: function (e) {
                //200成功， 500错误
                if (e.status == 200) {
                    layer.msg(e.message, {icon: 1, time: 2000}, function (index) {
                        if (e.status == 200) {
                            //关闭对话框
                            $("#roleModel").modal("hide");
                            //清空模态框（Modal）表单
                            document.getElementById("boxRoleForm").reset();
                            //刷新表格
                            $("#tb_departments").bootstrapTable('refresh');
                        }
                    });
                } else {
                    layer.msg(e.message, {icon: 2, time: 2000});
                }
            }
        })
    }


    //弹出隐藏层
    function authDiv(id) {
        var selectedRow = $('#tb_departments').bootstrapTable('getSelections');
        selectedRow = selectedRow[0];
        if (selectedRow == null || selectedRow.length == 0) {
            layer.msg("请选择要修改的记录");
            return false;
        }

        var rolesId = selectedRow.id;


        $("#roleModel input[name='roleId']").val(rolesId);

        // console.log(selectedRow)
        $.ajax({
            url: '/resources/queryResourcesListWithSelected',
            async: false,
            type: "POST",
            data: {id: rolesId},
            success: function (json) {
                var data = json.data;
                // console.log(data);
                var setting = {
                    check: {
                        enable: true
                    },
                    data: {
                        simpleData: {
                            enable: true
                        }
                    },
                    callback: {
                        onCheck: function (event, treeId, treeNode) {
                            // console.log(treeNode.tId + ", " + treeNode.name + "," + treeNode.checked);
                            // var treeObj = $.fn.zTree.getZTreeObj(treeId);
                            // var nodes = treeObj.getCheckedNodes(true);
                            // var ids = new Array();
                            // for (var i = 0; i < nodes.length; i++) {
                            //     //获取选中节点的值
                            //     ids.push(nodes[i].id);
                            // }
                            // console.log(ids);
                            // console.log(rolesId);
                            // $.post(options.saveRolesUrl, {"roleId": rolesId, "resourcesId": ids.join(",")}, function (obj) { }, 'json');
                        }
                    }
                };
                var zNodes= data;

                var code;

                function setCheck() {
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                        py = $("#py").attr("checked")? "p":"",
                        sy = $("#sy").attr("checked")? "s":"",
                        pn = $("#pn").attr("checked")? "p":"",
                        sn = $("#sn").attr("checked")? "s":"",
                        type = { "Y":py + sy, "N":pn + sn};
                    zTree.setting.check.chkboxType = type;
                    showCode('setting.check.chkboxType = { "Y" : "' + type.Y + '", "N" : "' + type.N + '" };');
                }
                function showCode(str) {
                    if (!code) code = $("#code");
                    code.empty();
                    code.append("<li>"+str+"</li>");
                }

                $(document).ready(function(){
                    var tree = $.fn.zTree.init($("#treeDemo"), setting, zNodes);
                    tree.expandAll(true);//全部展开
                    setCheck();
                    $("#py").bind("change", setCheck);
                    $("#sy").bind("change", setCheck);
                    $("#pn").bind("change", setCheck);
                    $("#sn").bind("change", setCheck);
                });


                $('#selectRole').modal('show');
            }
        });

        //显示编辑模态框
        $("#roleModel").modal("show");
    }

    //分配资源
    $("#tb_departments").on("click", "[id^='allot_']", function () {
        //主键id
        var uniqueId = $(this).attr("uniqueId");
        //获取单行信息
        var aa = $("#tb_departments").bootstrapTable('getRowByUniqueId', uniqueId);

        authDiv(uniqueId);
    });
</script>
</body>
</html>